<?php

namespace api\toilet\logic;

use api\admin\model\BandToiletModel;
use api\admin\model\BandToiletTagModel;
use api\admin\model\ToiletFlowModel;

class StoreallModel
{

    public $url     = "http://dev.meirenji.cn/oauth/token";
    public $headers = ['Content-Type: application/x-www-form-urlencoded'];

    /**
     * [getToken 获取每人记token]
     * @param  [type] $appId      [description]
     * @param  [type] $appSecret  [description]
     * @param  string $grant_type [description]
     * @return [type]             [description]
     */
    public function getToken($appId, $appSecret, $grant_type = "client_credentials")
    {

        $param = [
            "client_id" => $appId,
            "grant_type" => $grant_type,
            "client_secret" => $appSecret,
        ];

        $token = $this->mrjCurl($this->url, $param);
        if (!$token)
        {
            echo "！！！token";
            exit();
        }

        $tokenArr = json_decode($token, true);

        return $tokenArr['access_token'];
    }

    /**
     * [getCliFlowData 获取流量数据]
     * @Author   HUI
     * @DateTime 2019-01-22
     * @version  [version]
     * @return   [type]     [description]
     */
    public function getCliFlow($appId, $access_token)
    {

        $ToiletFlow = new ToiletFlowModel();
        $tag        = new BandToiletTagModel();

        $redis = new \Redis();
        $redis->connect('127.0.0.1', 6379);

        //判断关键数据是否丢失   toiletTag
        if (!$redis->get('toiletTag'))
        {
            $tag->addToiletTags();
        }

        $uris  = 'http://dev.meirenji.cn/api/v2/instance/strand';
        $uri   = 'http://dev.meirenji.cn/api/v2/devices';
        $param = [
            'appId' => $appId,
            'access_token' => $access_token,
        ];

        $flowData = $this->flowDataToEasy($appId, $access_token, $this->mrjCurl($uris, $param));
        $result   = $this->mrjCurl($uri, $param);
        $macArr   = json_decode($result, true);
        if (isset($macArr['content']) && count($macArr['content']) > 1)
        {
            foreach ($macArr['content'] as $key => $value)
            {
                $BandToilet = new BandToiletModel();
                $toiletRes  = $BandToilet->getBandToiletFields(['mac' => $value['imei']]);
                if (!empty($toiletRes) && isset($flowData[$value['openId']]))
                {
                    $RedisKey = $this->getRedisKey($toiletRes);
                    print_r($value['imei']);
                    echo "<br />___________________<br />";

                    //判断当前缓存是否被清空
                    if (!$redis->get($RedisKey . '_today_flow') || !$redis->get($RedisKey . '_all_flow'))
                    {

                        //判断当天缓存是否为空
                        if (!$redis->get($RedisKey . '_today_flow'))
                        {
                            $Flow['all'] = $ToiletFlow->where(['mac' => $value['imei']])->sum('user_in');
                        }

                    }

                    $newNum = (int) $flowData[$value['openId']]['in'] - $redis->get($RedisKey . '_today_flow');
                    $newNum = $newNum <= 0 ? 0 : $newNum;
                    //今日流量
                    $Flow['today'] = (int) $flowData[$value['openId']]['in'];
                    $redis->set($RedisKey . '_today_flow', (int) $flowData[$value['openId']]['in']);

                    if (date('H') > 23)
                    {
                        $redis->set($RedisKey . '_today_flow', 0);
                        $Flow['all'] = $redis->incr($RedisKey . '_all_flow', (int) $flowData[$value['openId']]['in']);
                    }
                    else
                    {
                        $Flow['all'] = $redis->incr($RedisKey . '_all_flow', $newNum);
                    }

                    //累计流量
                    $redis->hset($RedisKey, trim($toiletRes['mac']), serialize($Flow)); //

                    //当天流量插入数据库
                    $toiletData = [
                        'mac' => $value['imei'],
                        'user_in' => $redis->get($RedisKey . '_today_flow'),
                        'master_mac' => $toiletRes['master_mac'],
                    ];
                    $ToiletFlow->insertFlowData($toiletData);
                    //
                    $redisResult = $redis->hgetall($RedisKey);
                    $redis->hset('cloud_' . $toiletRes['master_mac'], trim($RedisKey), serialize($redisResult)); //
                }

            }

            return 'cloud_' . $toiletRes['master_mac'];
        }
    }

    /**
     * [flowDataToEasy 整理请求到的数据]
     * @Author   HUI
     * @DateTime 2019-01-22
     * @version  [version]
     * @param    string     $value [description]
     * @return   [type]            [description]
     */

    public function flowDataToEasy($appId, $access_token, $data)
    {

        $data    = json_decode($data, true);
        $flowTmp = [];
        foreach ($data['content'] as $key => $value)
        {
            $fiveUrl = 'http://dev.meirenji.cn/api/v2/instance/detail';
            $par     = [
                'appId' => $appId,
                'access_token' => $access_token,
                'openId' => $value['instanceOpenId'],
            ];
            $results          = json_decode($this->mrjCurl($fiveUrl, $par), true);
            $arrKey           = $results['content']['passageways']['0']['devices']['0']['openId'];
            $flowTmp[$arrKey] = ['in' => $value['in'], 'out' => $value['out']];
        }

        return $flowTmp;
    }

    /**
     * [getAuthToken curl 通用函数]
     * @Author   HUI
     * @DateTime 2019-01-22
     * @version  [version]
     * @param    [type]     $uri    [description]
     * @param    [type]     $post   [description]
     * @param    [type]     $header [description]
     * @return   [type]             [description]
     */
    public function mrjCurl($uri, $param)
    {
        $curl = curl_init();
        //设置抓取的url
        curl_setopt($curl, CURLOPT_URL, $uri);
        //设置头文件的信息作为数据流输出
        curl_setopt($curl, CURLOPT_HEADER, 1);
        //设置获取的信息以文件流的形式返回，而不是直接输出。
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        //设置post方式提交
        curl_setopt($curl, CURLOPT_POST, 1);
        //设置post数据
        curl_setopt($curl, CURLOPT_HTTPHEADER, $this->headers);
        curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($param));
        //执行命令
        $data = curl_exec($curl);
        //显示获得的数据
        if (curl_getinfo($curl, CURLINFO_HTTP_CODE) == '200')
        {
            $headerSize = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
            $header     = substr($data, 0, $headerSize);
            $body       = substr($data, $headerSize);
        }
        //关闭URL请求
        curl_close($curl);
        if (isset($body) && !empty($body))
        {
            return $body;
        }
        else
        {
            return false;
        }

    }

    public function getRedisKey($array = [])
    {

        // cloud_mac 此MAC所有信息
        // cloud_mac_device 此MAC设备类型下的所有信息
        // cloud_mac_device_man 此MAC设备类型男厕下的所有信息
        // cloud_mac_device_man_mini[mac] 此MAC设备类型男厕下单设备的信息
        $redis = new \Redis();
        $redis->connect('127.0.0.1', 6379);
        $mac_device_type = ['flow', 'device', 'sensor'];
        $Tag             = $redis->get('toiletTag');
        foreach (unserialize($Tag) as $key => $value)
        {
            if ($array['tag_id'] == $value['id'])
            {
                $device = $value;
            }
        }
        if (empty($device))
        {
            return 0;
        }
        //1.tag写入缓存
        //2.主设备状态写入缓存 5min
        //2.单设备状态写入缓存 5min
        return 'cloud_' . $array['master_mac'] . '_' . $mac_device_type[$array['mac_device_type'] - 1] . '_' . $device['tag_as_name'];
    }

}
